import 'dart:async';
import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/provider/UserModel.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/model/base_entity.dart';
import 'package:flutter_juwo/ui/model/sim_code_entity.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:provider/provider.dart';
import 'model/loginbysms_entity.dart';
import 'pin_input_text_field.dart';

///************************
/// @auther nb
/// @function 验证码
/// @创建日期 2019/8/13 14:59
///************************
class VerifyCode extends StatefulWidget {
  final String phoneNum;
  final int type;

  const VerifyCode(this.phoneNum, this.type);

  @override
  _VerifyCodeState createState() => _VerifyCodeState();
}

class _VerifyCodeState extends State<VerifyCode> {
  int line1Color = 0xFFe5e5e5;

  FocusNode _nameFocusNode;
  TextEditingController _controller;
  String _verifyStr = '获取验证码';

  bool isClickable = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _nameFocusNode = FocusNode();
    _controller = TextEditingController();
    _nameFocusNode.addListener(() {
      if (_nameFocusNode.hasFocus) {
        print("name 获取到焦点");
        setState(() {
          line1Color = 0xFFdf3033;
        });
      } else {
        setState(() {
          line1Color = 0xFFe5e5e5;
        });
      }
    });

    _startTimer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: <Widget>[
          ///x
          getRow1(),

          ///登录
          getRow2(),
          getRow3(),
          getVerifyCode(),
          /*     VerificationCodeView(4, (String result) {
            print("输入的内容：${result}");
          }),*/

          getRow5()
        ],
      ),
    );
  }

  getRow1() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          MediaQueryData.fromWindow(window).padding.top, 0, 0),
      height: ScreenUtil().setWidth(88),
      child: GestureDetector(
        onTap: () {
          Application.router.pop(context);
        },
        child: Image.asset(
          Utils.getImgPath("icon_left"),
          width: ScreenUtil().setWidth(32),
          height: ScreenUtil().setWidth(32),
        ),
      ),
    );
  }

  getRow2() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(92), ScreenUtil().setWidth(88), 0, 0),
      alignment: Alignment.centerLeft,
      child: Text(
        "短信验证码",
        style: TextStyle(
          fontSize: ScreenUtil().setWidth(48),
          color: Colours.appC1,
          fontFamily: Font.PingFangBlod,
        ),
        /*TextStyles.custom(48, Colours.appC1, AppFontFamily.PingFangBlod)*/
      ),
    );
  }

  getRow3() {
    return Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(90), ScreenUtil().setWidth(30), 0, 0),
        alignment: Alignment.centerLeft,
        child: Text(
          "短信验证码已发送至${widget.phoneNum}",
          style: TextStyles.custom(
              24, Color(0xFF666666), Font.PingFangMedium),
        ));
  }

  getVerifyCode() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(90),
          ScreenUtil().setWidth(110), ScreenUtil().setWidth(90), 0),
      child: PinInputTextField(
        pinLength: 4,
        decoration: BoxLooseDecoration(
            textStyle: TextStyle(
              color: Colors.black,
              fontSize: 24,
            ),
            strokeColor: Color(0xFFE5E5E5),
            radius: Radius.circular(2),
            strokeWidth: ScreenUtil().setWidth(1),
            gapSpace: ScreenUtil().setWidth(12)
            //  enteredColor: Colors.deepOrange,
            ),
        controller: _controller,
        autoFocus: true,
        textInputAction: TextInputAction.go,
        enabled: true,
        onSubmit: (pin) {
          if (pin.length == 4) {
            this.confirmsmscode(pin);
          }
        },
      ),
    );
  }

  getRow5() {
    return InkWell(
      onTap: () {
        if (isClickable) {
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return new LoadingDialog(
                  text: "正在发送验证码…",
                );
              });
          _getsmscode();
        }
      },
      child: Container(
        margin: EdgeInsets.only(
            top: ScreenUtil().setWidth(42), bottom: ScreenUtil().setWidth(42)),
        alignment: Alignment.center,
        child: Text(
          '$_verifyStr',
          textAlign: TextAlign.center,
          style: isClickable
              ? TextStyles.custom(
                  24, Color(0xFFdf3033), Font.PingFangMedium)
              : TextStyles.custom(
                  24, Colours.appC3, Font.PingFangMedium),
        ),
      ),
    );
  }

  void confirmsmscode(String pin) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new LoadingDialog(
            text: "正在验证验证码…",
          );
        });

    if (widget.type == 1) {
      _start(pin);
    } else {
      _verCode(pin);
    }
  }

  Future _verCode(String pin) async {
    FormData params =
        FormData.from({"tel": widget.phoneNum, "smsCode": pin, "type": "2"});
    DioManager.getInstance().post(Api.CONFIRMSMSCODE, params,
        //正常回调
        (data) {
      print("验证验证码去修改密码:$data");
      BaseEntity loginEntity = BaseEntity.fromJson(data);
      if (loginEntity == null) {

        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        Navigator.pop(context);
        //清空验证码输入区域
        _controller.clear();
        return;
      }

      if (loginEntity.code == Api.SUCCESS_CODE) {
        ///设置密码页面
        Navigator.pop(context);
        NavigatorUtils.push(context, "${Routes.setPwd}?type=2&tel=${widget.phoneNum}&smsCode=$pin", replace: true);
        return;
      }

      if (loginEntity.code == Api.ERROR_CODE ||
          loginEntity.code == Api.ERROR_CODE) {
        ToastUtil.showShortErrToast(loginEntity.message);
        Navigator.pop(context);
        //清空验证码输入区域
        _controller.clear();
      }
    },
        //错误回调
        (error) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      Navigator.pop(context);
    }, isToken: false);
  }

  Future _start(String pin) async {
    FormData params = FormData.from({"tel": widget.phoneNum, "smsCode": pin});
    DioManager.getInstance().post(Api.LOGINBYSMS, params,
        //正常回调
        (data) {
      print("短信验证码登录:$data");
      LoginbysmsEntity loginEntity = LoginbysmsEntity.fromJson(data);
      if (loginEntity == null) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        Navigator.pop(context);
        //清空验证码输入区域
        _controller.clear();
        return;
      }

      if (loginEntity.code == Api.SUCCESS_CODE) {
        if (loginEntity.data.isPwd == 1) {
          SpUtil.putString(SpKeys.userToken, loginEntity.data.token);
          SpUtil.putString(SpKeys.userPhone, widget.phoneNum);
          Provider.of<UserModel>(context).updateToken(loginEntity.data.token);
          Navigator.pop(context);
          ///设置密码页面
          NavigatorUtils.push(context, "${Routes.setPwd}?type=1&tel=${widget.phoneNum}&smsCode=$pin", replace: true);
        } else {
          ///保存 token 、手机号
          SpUtil.putString(SpKeys.userToken, loginEntity.data.token);
          SpUtil.putString(SpKeys.userPhone, widget.phoneNum);
          Provider.of<UserModel>(context).updateToken(loginEntity.data.token);
          setState(() {
            //跳转到相应页面
            ToastUtil.showShortToast("登录成功");
            Navigator.pop(context);
            Navigator.pop(context);
            Navigator.pop(context);
          });
        }

        return;
      }

      if (loginEntity.code == Api.ERROR_CODE ||
          loginEntity.code == Api.ERROR_CODE) {
        ToastUtil.showShortErrToast(loginEntity.message);
        Navigator.pop(context);
        //清空验证码输入区域
        _controller.clear();
      }
    },
        //错误回调
        (error) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      Navigator.pop(context);
    }, isToken: false);
  }

  Future _getsmscode() async {
    //17099298919  bin110123
    FormData params = FormData.from({"tel": widget.phoneNum, "type": "3"});
    DioManager.getInstance().post(Api.GETSMSCODE, params,
        //正常回调
        (data) {
      print("获取验证码:$data");

      SimCodeEntity simCodeEntity = SimCodeEntity.fromJson(data);
      print(simCodeEntity.code == Api.SUCCESS_CODE);

      if (simCodeEntity.code == Api.SUCCESS_CODE) {
        Navigator.pop(context);
        _startTimer();
        return;
      }

      if (simCodeEntity.code == Api.ERROR_CODE ||
          simCodeEntity.code == Api.ERROR_CODE_0) {
        Navigator.pop(context);
        ToastUtil.showShortErrToast(simCodeEntity.message);
        return;
      }
      Navigator.pop(context);
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
    },
        //错误回调
        (error) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      Navigator.pop(context);
    }, isToken: false);
  }

  /// 倒计时的计时器。
  Timer _timer;

  /// 当前倒计时的秒数。
  int _seconds = 30;

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _cancelTimer();
        setState(() {
          isClickable = true;
          _seconds = 30;
        });
        return;
      }

      if (mounted) {
        setState(() {
          isClickable = false;
          _seconds--;
          _verifyStr = '已发送$_seconds' + 's后可重新发送';

          if (_seconds == 0) {
            isClickable = true;
            _verifyStr = '重新发送';
          }
        });
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
  }
}
